package cn.kooki.app.duobao.ui.Activity.User;

import android.animation.ValueAnimator;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.animation.ValueAnimatorCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseNavActivity;
import cn.kooki.app.duobao.core.APIService;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.User.UserPointItem;
import cn.kooki.app.duobao.data.Bean.User.UserPointStatusResponse;
import cn.kooki.app.duobao.data.Bean.base.BaseResponse;
import cn.kooki.app.duobao.data.bus.ChangePageEvent;
import cn.kooki.app.duobao.data.bus.SignSusEvent;
import cn.kooki.app.duobao.data.bus.UserRefrshEvent;
import cn.kooki.app.duobao.data.constant.Constants;
import cn.kooki.app.duobao.ui.Adapter.PointsAdapter;
import cn.kooki.app.duobao.ui.Adapter.ShareDialogAdapter;
import cn.kooki.app.duobao.ui.widget.CustomRelativeLayout;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.ShareUtils;
import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;


/**
 * Created by xiong on 2016/1/8.
 */
public class UserPointsActivity extends BaseNavActivity implements View.OnClickListener {
    @Bind(R.id.tv_me_points_current_value)
    TextView tvMePointsCurrentValue;
    @Bind(R.id.tv_me_points_current)
    TextView tvMePointsCurrent;
    @Bind(R.id.tv_me_points_to_coin)
    TextView tvMePointsToCoin;
    @Bind(R.id.iv_me_points_sign_dialog_show)
    ImageView ivMePointsSignDialogShow;
    @Bind(R.id.btn_me_points_exchange)
    Button btnMePointsExchange;
    @Bind(R.id.recycler_me_points_sign)
    RecyclerView recyclerMePointsSign;
    @Bind(R.id.iv_me_points_sign)
    ImageView ivMePointsSign;
    @Bind(R.id.btn_me_points_share)
    Button btnMePointsShare;
    @Bind(R.id.btn_me_points_partake)
    Button btnMePointsPartake;
    @Bind(R.id.btn_me_points_address)
    Button btnMePointsAddress;
    @Bind(R.id.btn_me_points_info)
    Button btnMePointsInfo;
    @Bind(R.id.root_scroll)
    ScrollView rootScroll;
    @Bind(R.id.loadingWrapper)
    CustomRelativeLayout loadingWrapper;

    @Bind(R.id.layout_points_tips)
    View layoutPointsTips;

    private PointsAdapter pointsAdapter;
    private UserInfo userinfo;
    private UserPointItem data;

    public static final int TYPE_SING = 4;
    public static final int TYPE_SHARE = 3;
    public static final int TYPE_EXCHANGE = 90;

    public int lastpoints = 50;
    private AlertDialog alertDialog;
    private UserPointStatusResponse resdata;
    private View dialogview;
    private GridView gridview;
    private String content;
    private String url;


    @Override
    public void setLayoutContainerView() {
        setContainerView(R.layout.fragment_me_points);
        ButterKnife.bind(this);

    }


    private ArrayList<Integer> potins = new ArrayList<>();
    private int currtday = 0;
    private boolean issign = false;

    @Override
    protected void afterView() {
        setTitle("积分中心");
        rootScroll.setVisibility(View.GONE);
        loadingWrapper.showloading();
        recyclerMePointsSign.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        pointsAdapter = new PointsAdapter(potins);
        LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(this, R.anim.list_layout_animi);
        recyclerMePointsSign.setLayoutAnimation(animation);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            recyclerMePointsSign.setAdapter(pointsAdapter);
        }
        ivMePointsSign.setOnClickListener(this);
        userinfo = SharePreferencesUtils.getUserinfo(this);
        layoutPointsTips.setOnClickListener(this);
        btnMePointsShare.setOnClickListener(this);
        btnMePointsExchange.setOnClickListener(this);
        btnMePointsAddress.setOnClickListener(this);
        btnMePointsPartake.setOnClickListener(this);
        btnMePointsInfo.setOnClickListener(this);
        getPointsStatus();
    }

    private void getPointsStatus() {
        MainFactory.getApiInstance().getPotionsStatus(userinfo.getUid(), new Callback<UserPointStatusResponse>() {
            @Override
            public void success(UserPointStatusResponse baseResponse, Response response) {

                if (baseResponse.getStatus() == 0) {
                    resdata = baseResponse;
                    refreshView();

                }
                hideloading();
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    private void hideloading() {
        loadingWrapper.hideloading();
        rootScroll.setVisibility(View.VISIBLE);
    }

    private void refreshView() {
        ivMePointsSign.setSelected(resdata.data.qd);
        btnMePointsInfo.setEnabled(!resdata.data.wszl);
        btnMePointsShare.setEnabled(!resdata.data.fx);
        btnMePointsAddress.setEnabled(!resdata.data.shdz);
        currtday = resdata.qdcs - (resdata.data.qd ? 1 : 0);
        potins.clear();
        potins.addAll(resdata.date);
        issign = resdata.data.qd;
        if (issign) {
            SharePreferencesUtils.putLong(this, "signtime", SystemClock.currentThreadTimeMillis());
        }
        SharePreferencesUtils.putBoolean(UserPointsActivity.this, "isSign", issign);
        EventBus.getDefault().post(new SignSusEvent());
        SpannableString coin = new SpannableString("= " + resdata.integral / 1000 + "个抢宝币(1000:1)");
        coin.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.link)), 1, (resdata.integral / 1000 + "").length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvMePointsToCoin.setText(coin);
        pointsAdapter.setIssing(issign);
        pointsAdapter.setCurrtday(currtday);
        pointsAdapter.notifyDataSetChanged();
        ValueAnimator valueAnimator = ValueAnimator.ofInt(lastpoints, resdata.integral);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();
                tvMePointsCurrentValue.setText(value + "");
            }
        });
        valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        valueAnimator.setDuration(1000);
        valueAnimator.start();

        lastpoints = resdata.integral;
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    public void onEnterAnimationComplete() {
        super.onEnterAnimationComplete();
        recyclerMePointsSign.setAdapter(pointsAdapter);
    }

    @Override
    public void onClick(View v) {
        if (v == ivMePointsSign) {
            if (!ivMePointsSign.isSelected()) {
                showLoading("正在签到");
                MainFactory.getApiInstance().userPoints(TYPE_SING, userinfo.getUid(), new Callback<BaseResponse>() {
                    @Override
                    public void success(BaseResponse baseResponse, Response response) {
                        if (baseResponse.getStatus() == 0) {

                            getPointsStatus();
                            dismissLoading();
                        } else {
                            showToastMessage("今日已签到");
                            dismissLoading();
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        dismissLoading();
                    }
                });
            }
        }
        if (v == layoutPointsTips) {
            showtipsDiloag();
        }
        if (v == btnMePointsExchange) {
            exchangeValue();
        }
        if (v == btnMePointsPartake) {
            EventBus.getDefault().post(new ChangePageEvent());
            finish();
        }
        if (v == btnMePointsShare) {

            showShareDialog();

        }
        if (v == btnMePointsAddress) {
            intent(ShipAddressActivity.class);
        }
        if (v == btnMePointsInfo) {

            intent(UserinfoActivity.class);
        }
    }

    private void exchangeValue() {
        if (resdata != null && resdata.integral / 1000 > 0) {

            showLoading("正在兑换");
            MainFactory.getApiInstance().userPoints(TYPE_EXCHANGE, userinfo.getUid(), new Callback<BaseResponse>() {
                @Override
                public void success(BaseResponse baseResponse, Response response) {
                    dismissLoading();
                    if (baseResponse.getStatus() == 0) {
                        EventBus.getDefault().post(new UserRefrshEvent());
                        getPointsStatus();
                        showToastMessage("兑换成功");
                    } else {
                        showToastErrorMessage(baseResponse.getMsg());
                    }
                }

                @Override
                public void failure(RetrofitError error) {
                    dismissLoading();

                }
            });
        } else {
            showToastMessage("积分不足，无法兑换");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (loadingWrapper != null) {
            getPointsStatus();
        }
    }


    private void showShareDialog() {
        content = "一元收获惊喜，亲测有效！现在我把好运气人品都传给你，快来领取吧！";
        final String title = "朋友夺到宝，分给你了！";
        final UMImage image = new UMImage(this, R.drawable.takeout_ic_coupon_wm);
        ShareUtils shareUtils = new ShareUtils();
        url = Constants.APP_SHARE_URL+userinfo.getUid();
        final String finalTitle = title;
        shareUtils.showShareDialog(this, new ShareUtils.shareItemClickLister() {
            @Override
            public void onClick(SHARE_MEDIA media) {
                if (media == SHARE_MEDIA.SINA) {
                    content = content + url;
                }
                new ShareAction(UserPointsActivity.this)
                        .setPlatform(media)
                        .setCallback(umShareListener).withTitle(finalTitle).withMedia(image)
                        .withText(content).withTargetUrl(url)
                        .share();
            }
        });
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA share_media) {
            showToastMessage("分享成功");
            MainFactory.getApiInstance().userPoints(TYPE_SHARE, userinfo.getUid(), new Callback<BaseResponse>() {
                @Override
                public void success(BaseResponse baseResponse, Response response) {
                    if (baseResponse.getStatus() == 0) {
                        getPointsStatus();
                    }
                }

                @Override
                public void failure(RetrofitError error) {

                }
            });
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            showToastMessage("分享失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            showToastMessage("分享取消");
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    private void showtipsDiloag() {

        View inflate = LayoutInflater.from(this).inflate(R.layout.diloag_user_points_tips, null);
        TextView tv_content_points = (TextView) inflate.findViewById(R.id.tv_content_points);
        tv_content_points.setText(Html.fromHtml(tv_content_points.getText().toString()));
        new AlertDialog.Builder(this).setView(inflate).setNegativeButton("确定", null).show();
    }


}
